package cn.shop.admin.controller;

import cn.hutool.core.util.StrUtil;
import cn.shop.admin.service.FundDetailService;
import cn.shop.admin.service.MerchantUserService;
import cn.shop.base.MyPage;
import cn.shop.transcation.detail.entity.FundDetail;
import cn.shop.transcation.detail.entity.WithdrawDetail;
import cn.shop.transcation.merchantUser.mapper.entity.MerchantUser;
import cn.shop.utils.ApiResult;
import cn.shop.utils.PageUtil;
import cn.shop.utils.Putif;
import cn.shop.utils.constant.Constant;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 交易明细(FundDetail)表控制层
 *
 * @author jzw
 * @since 2021-12-06 14:22:11
 */
@Validated
@RestController
@RequestMapping("/api/v1/fundDetail")
public class FundDetailController {

	/**
	 * 服务对象
	 */
	@Resource
	private FundDetailService fundDetailService;
	@Resource
	private MerchantUserService merchantUserService;

	/**
	 * 分页查询所有数据
	 *
	 * @return 所有数据
	 * @author jzw
	 * @since 2021-12-06 14:22:11
	 */
	@GetMapping("queryByPageForPub")
	public ApiResult<Map<String, Object>> queryByPageForPub() {
		LambdaQueryWrapper<FundDetail> query = Wrappers.<FundDetail>lambdaQuery()
				.in(FundDetail::getType, 0, 1);
		Page<FundDetail> page = Page.of(1, 20);
		page = fundDetailService.page(page, query);
		Map<String, Object> map = PageUtil.formatPage(page, f -> Putif.start()
				.anyway("amount", f.getAmount())
				.anyway("goods", f.getGoods())
				.anyway("playerAccount", StrUtil.hide(f.getPlayerAccount(), 3, f.getPlayerAccount().length() + 1))
				.get());
		return ApiResult.success(map);
	}

	/**
	 * 查询所有数据
	 *
	 * @param fundDetail 查询实体
	 * @return 所有数据
	 * @author jzw
	 * @since 2021-12-06 14:22:11
	 */
	@GetMapping("queryAll")
	public ApiResult<List<FundDetail>> queryAll(FundDetail fundDetail) {
		return ApiResult.success(fundDetailService.list(new QueryWrapper<>(fundDetail)));
	}

	/**
	 * 分页查询所有数据
	 *
	 * @param page   分页对象
	 * @param detail 查询实体
	 * @return 所有数据
	 * @author jzw
	 * @since 2021-12-06 14:22:11
	 */
	@GetMapping("queryByPage")
	public ApiResult<MyPage<FundDetail>> queryByPage(MyPage<FundDetail> page, FundDetail detail,
													 @RequestParam(required = false) String uaccount,
	                                                 @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime startTime,
	                                                 @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime endTime) {
		if (StrUtil.isNotBlank(uaccount)){
			MerchantUser user = merchantUserService.lambdaQuery().eq(MerchantUser::getAccount, uaccount).one();
			if (user == null) {
				detail.setUid(-1L);
			} else {
				detail.setUid(user.getId());
			}
		}
		LambdaQueryWrapper<FundDetail> query = Wrappers.<FundDetail>lambdaQuery()
				.eq(StrUtil.isNotBlank(detail.getGoods()), FundDetail::getGoods, detail.getGoods())
				.eq(detail.getOrderId() != null, FundDetail::getOrderId, detail.getOrderId())
				.eq(detail.getUid() != null, FundDetail::getUid, detail.getUid())
				.eq(detail.getPlayerId() != null, FundDetail::getPlayerId, detail.getPlayerId())
				.like(StrUtil.isNotBlank(detail.getPlayerAccount()), FundDetail::getPlayerAccount, detail.getPlayerAccount())
				.eq(detail.getType() != null, FundDetail::getType, detail.getType())
				.in(detail.getType() == null, FundDetail::getType, 0, 1, 2)
				.apply(startTime != null,
						"create_time >= {0}", startTime)
				.apply(endTime != null,
						"create_time <= {0}", endTime);

		return ApiResult.success(fundDetailService.page(page, query));
	}

	/**
	 * 分页查询所有数据
	 *
	 * @param page   分页对象
	 * @param detail 查询实体
	 * @return 所有数据
	 * @author jzw
	 * @since 2021-12-06 14:22:11
	 */
	@GetMapping("queryByPageForWithdraw")
	public ApiResult<MyPage<WithdrawDetail>> queryByPageForWithdraw(MyPage<FundDetail> page, FundDetail detail,
	                                                                @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime startTime,
	                                                                @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime endTime) {
		page.addOrder(OrderItem.desc("id"));
		QueryWrapper<FundDetail> query = Wrappers.<FundDetail>query()
				.eq(detail.getOrderId() != null, "fd.order_id", detail.getOrderId())
				.like(StrUtil.isNotBlank(detail.getPlayerAccount()), "fd.player_account", detail.getPlayerAccount())
				.eq("w.state", 3)
				.eq(detail.getType() != null, "fd.type", 3)
				.apply(startTime != null,
						"w.payment_time >={0}", startTime)
				.apply(endTime != null,
						"w.payment_time <= {0}", endTime);

		return ApiResult.success(fundDetailService.queryByPageForWithdraw(page, query));
	}

	/**
	 * 统计金额
	 *
	 * @return 返回结果
	 */
	@GetMapping("/statisticsForWithdraw")
	public ApiResult<Map<String, BigDecimal>> statisticsForWithdraw(FundDetail fundDetail,
	                                                                @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime startTime,
	                                                                @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime endTime) {
		return ApiResult.success(fundDetailService.statisticsForWithdraw(fundDetail, startTime, endTime));
	}

	/**
	 * 统计金额
	 *
	 * @return 返回结果
	 */
	@GetMapping("/statistics")
	public ApiResult<Map<String, BigDecimal>> statistics(FundDetail fundDetail,
														 @RequestParam(required = false) String uaccount,
	                                                     @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime startTime,
	                                                     @RequestParam(required = false) @DateTimeFormat(pattern = Constant.DATETIME_FORMAT) LocalDateTime endTime) {
		if (StrUtil.isNotBlank(uaccount)){
			MerchantUser user = merchantUserService.lambdaQuery().eq(MerchantUser::getAccount, uaccount).one();
			if (user == null) {
				fundDetail.setUid(-1L);
			} else {
				fundDetail.setUid(user.getId());
			}
		}
		return ApiResult.success(fundDetailService.statistics(fundDetail, startTime, endTime));
	}

	/**
	 * 通过主键查询单条数据
	 *
	 * @param id 主键
	 * @return 单条数据
	 * @author jzw
	 * @since 2021-12-06 14:22:11
	 */
	@GetMapping("queryOne/{id}")
	public ApiResult<FundDetail> selectOne(@PathVariable Serializable id) {
		return ApiResult.success(fundDetailService.getById(id));
	}

	/**
	 * 删除单条数据
	 *
	 * @param id 主键
	 * @return 删除结果
	 * @author jzw
	 * @since 2021-12-06 14:22:11
	 */
	@DeleteMapping("delete/{id}")
	public ApiResult<Map<String, Object>> delete(@PathVariable Long id) {
		FundDetail fundDetail = new FundDetail();
		fundDetail.setId(id);
		return ApiResult.result(fundDetailService.removeById(fundDetail));
	}


}

